<template>
  <status-bar />
  <view class="login-page f fd-col ai-c jc-c w100">
    <bg-set background="linear-gradient(#c7e5ff,#f1f6fc)" />
    <view class="login-page__img_part f fd-col ai-c">
      <image
        class="login-page__img_part_img"
        src="/static/image/login/lm.png"
      ></image>
      <text class="login-page__img_part_title">物流管理APP</text>
    </view>
    <view class="login-page__form-part f1">
      <uni-card
        title="请登录"
        mode="basic"
        :is-shadow="true"
        note="Tips"
        class="login-page__form-part-card"
      >
        <uni-forms ref="form" :rules="rules" :modelValue="formData">
          <uni-forms-item label="用户名" name="name" :required="true"
            ><uni-easyinput
              v-model="userName"
              :inputBorder="false"
              placeholder="请输入用户名"
              trim="both"
          /></uni-forms-item>
          <uni-forms-item label="手机号" name="phoneNumber" :required="true"
            ><uni-easyinput
              v-model="userPhone"
              :inputBorder="false"
              placeholder="请输入正确的手机号码"
              trim="both"
          /></uni-forms-item>
          <uni-forms-item label="密码" name="password" :required="true"
            ><uni-easyinput
              v-model="userPwd"
              :inputBorder="false"
              placeholder="请输入密码"
              type="password"
              trim="both"
          /></uni-forms-item>
        </uni-forms>
        <view class="f jc-sa mt60">
          <van-button type="primary" @click="submit" round style="width: 30%"
            >登录</van-button
          >
          <van-button type="primary" @click="register" round style="width: 30%">
            注册
          </van-button>
        </view>
      </uni-card>
    </view>
  </view>
</template>

<script>
import { ref, toRefs, reactive } from "vue";
import loginPageAPI from "/api/modules/login";
import storageOperation from "/utils/index";
export default {
  name: "login-page",
  setup() {
    const form = ref(null);
    const toastStatus = ref(0);
    const formData = reactive({
      userName: storageOperation.getStorageSync("userName").value,
      userPhone: storageOperation.getStorageSync("userPhone").value,
      userPwd: "",
    });
    const toastMessage = [
      "用户名或手机号或密码错误,请核对后重新输入!",
      "该用户名已存在,换一个昵称试试呢!",
      "该手机号已注册过但与用户名不匹配,请核对后重新输入!",
    ];
    const rules = {
      // 对name字段进行必填验证
      name: {
        rules: [
          {
            required: true,
            errorMessage: "用户名不能为空!",
          },
        ],
      },
      phoneNumber: {
        rules: [
          {
            required: true,
            errorMessage: "手机号码不能为空!",
          },
          {
            validateFunction: (rule, value, data, callback) => {
              // 异步需要返回 Promise 对象
              return new Promise((resolve, reject) => {
                const reg = /^1[3|4|5|7|8]\d{9}$/;
                setTimeout(() => {
                  if (reg.test(value)) {
                    // 通过返回 resolve
                    resolve();
                  } else {
                    // 不通过返回 reject(new Error('错误信息'))
                    reject(new Error("手机号码格式错误!"));
                  }
                }, 0);
              });
            },
          },
        ],
      },
      password: {
        rules: [
          {
            required: true,
            errorMessage: "密码不能为空!",
          },
          {
            validateFunction: (rule, value, data, callback) => {
              // 异步需要返回 Promise 对象
              return new Promise((resolve, reject) => {
                setTimeout(() => {
                  if (value.length >= 6) {
                    // 通过返回 resolve
                    resolve();
                  } else {
                    // 不通过返回 reject(new Error('错误信息'))
                    reject(new Error("密码长度必须在6位及以上!"));
                  }
                }, 0);
              });
            },
          },
        ],
      },
    };
    const submit = () => {
      form.value
        .validate()
        .then((res) => {
          console.log("表单数据信息：", res);
          loginPageAPI
            .loginQuery(formData)
            .then((res) => {
              const data = res;
              const { userName, userPhone, userPwd } = data[0] || {};
              if (data.length) {
                storageOperation.setStorage("loginStatus", true);
                storageOperation.setStorage("userName", userName);
                storageOperation.setStorage("userPhone", userPhone);
                storageOperation.setStorage("userPwd", userPwd);
                storageOperation.setStorageSync("fromPage", "login-page");
                uni.switchTab({
                  url: "/pages/home/home",
                });
              } else {
                uni.showToast({
                  title: toastMessage[toastStatus.value],
                  icon: "none",
                  duration: 2000,
                  position: "top",
                });
              }
            })
            .catch((err) => {
              console.log(err);
            });
        })
        .catch((err) => {
          console.log("表单错误信息：", err);
        });
    };
    const register = () => {
      form.value
        .validate()
        .then((res) => {
          console.log("表单数据信息：", res);
          loginPageAPI
            .loginQueryName({ userName: formData.userName })
            .then((res) => {
              const data = res;
              if (data.length) {
                toastStatus.value = 1;
                uni.showToast({
                  title: toastMessage[toastStatus.value],
                  icon: "none",
                  duration: 2000,
                  position: "top",
                });
                return;
              } else {
                loginPageAPI
                  .loginQueryPhone({ userPhone: formData.userPhone })
                  .then((res) => {
                    const data = res;
                    if (data.length && data.length === 1) {
                      if (data[0].userName != formData.userName) {
                        toastStatus.value = 2;
                        uni.showToast({
                          title: toastMessage[toastStatus.value],
                          icon: "none",
                          duration: 2000,
                          position: "top",
                        });
                        return;
                      }
                    } else if (data.length === 0) {
                      loginPageAPI
                        .loginInsert(formData)
                        .then((res) => {
                          const { userName, userPhone } = toRefs(formData);
                          storageOperation.setStorage("loginStatus", true);
                          storageOperation.setStorage(
                            "userName",
                            userName.value
                          );
                          storageOperation.setStorage(
                            "userPhone",
                            userPhone.value
                          );
                          storageOperation.setStorageSync("fromPage", "login-page");
                          uni.switchTab({
                            url: "/pages/home/home",
                          });
                        })
                        .catch((err) => {
                          console.log(err);
                        });
                    }
                  })
                  .catch((err) => console.log(err));
              }
            })
            .catch((err) => console.log(err));
        })
        .catch((err) => {
          console.log("表单错误信息：", err);
        });
    };
    return {
      form,
      toastStatus,
      toastMessage,
      formData,
      ...toRefs(formData),
      rules,
      submit,
      register,
    };
  },
};
</script>
<style lang="scss" scoped>
.login-page {
  position: fixed;
  width: 100%;
  height: 100vh;
  &__img_part {
    margin-top: 200rpx;
    &_img {
      width: 192rpx;
      height: 144rpx;
    }
    &_title {
      font-size: 40rpx;
      letter-spacing: 10rpx;
    }
  }
  &__form-part {
    margin-top: 100rpx;
    width: 100%;
    &-card {
      height: 100%;
      margin: 0 !important;
      background: transparent;
      border: 0;
      box-shadow: none !important;
      ::v-deep .uni-card__header {
        border-bottom: 1px solid #ccc;
      }
      ::v-deep .uni-forms-item__label {
        .label-text {
          font-size: 30rpx !important;
        }
      }
      ::v-deep .uni-easyinput__content {
        border-bottom: 1px solid #000;
        border-color: #ccc !important;
      }
      ::v-deep .uni-input-placeholder {
        font-size: 30rpx !important;
      }
      ::v-deep .uni-input-input {
        font-size: 30rpx !important;
      }
      ::v-deep .van-button__text {
        font-size: 30rpx;
      }
    }
  }
}
</style>
